package NG::Gen::Users::Secure;
use strict;
use warnings;
use utf8;

use Digest::MD5 qw(md5_hex);
use Time::HiRes qw(gettimeofday);
use NG::Sys::Datetime;
use NG::Sys::Text;

sub enter_user {
	my ($self,$auth_type,$ip) = @_;
	if($self->online){
		$self->close_session($self->session_start,$self->checked);
	}
	my $key = md5_hex(scalar gettimeofday(),rand());
	my $now = unixtime2timestamp();
	$self->update_data(
					session => $key,
					vk => (111111+int rand(88888)),
					session_ip => $ip,
					session_start => $now,
					chat_pass => (11111111+int rand(8888888)),
					online => 1,
					checked => $now,
					auth_type => $auth_type,
				);
	if($auth_type){
		if(my $auth = $self->auth->get_by_key($auth_type,1)){
			if(@$auth){
				$auth->[0]->date_last($now);
			}
		}
	}
	$self->after_enter;
	return $key;
}
sub check_session {
	my ($self,$session) = @_;
	my $vs;
	return $session && ($vs = $self->session) && $vs eq $session;
}
sub check_online {
	my ($self) = @_;
	$self->update_data(online => 1,checked => unixtime2timestamp());
}
sub exit_user {
	my ($self) = @_;
	my $now = unixtime2timestamp();
	$self->update_data(session => undef, online => 0, checked => $now);
	my $ret = $self->close_session($self->session_start,$now);
	$self->after_exit;
	return $ret;
}
sub close_session {
	my ($self,$start,$end) = @_;
	unless($start and $end){
		return;
	}
	my $t_start = timestamp2unixtime($start);
	my $t_end = timestamp2unixtime($end);
	unless($t_start and $t_end){
		return;
	}
	$self->{parent}{dbh}->Insert(log_session => {
		user_id => $self->{id},
		start => $start,
		end => $end,
		ip => $self->session_ip,
		duration => $t_end - $t_start,
		auth_type => $self->auth_type,
		});
}
sub rename_user {
	my ($self,$login) = @_;
	if($self->auth->length == 0){
		return "Трубуется привязка входа";
	}
	unless(check_login_valid($self->chat_login)){
		return "Логин уже установлен";
	}
	if(my $err = check_login_valid($login)){
		return $err;
	}
	if($self->{parent}->check_login($login)){
		return "Логин '$login', не доступен";
	}
	my $now = unixtime2timestamp();
	my $old_login = $self->chat_login;
	my %data = (
			chat_login => $login,
			title => $login,
		);
	$self->update_data(\%data);
	$self->after_rename($old_login);
	return undef;
}

1;
